#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

#define NUM_THREAD 6

void * thread_function(void * arg);

int fakelock=1;
pthread_mutex_t mutex;

int main()
{
    int res;
    pthread_t a_thread[NUM_THREAD];
    void * thread_result;
    int lots_of_threads;

    pthread_mutex_init(&mutex,0);

    for (lots_of_threads = 0;lots_of_threads < NUM_THREAD; lots_of_threads++){
	    //使用fakelock来查看子线程是否创建完成，如果不完成则随眠一下，或稍后以lock堵塞一下。

	    while(!fakelock) {
	    }
	    pthread_mutex_lock(&mutex);
	    fakelock = 0;
	    pthread_mutex_unlock(&mutex);

            res = pthread_create(&(a_thread[lots_of_threads]),NULL,thread_function,&lots_of_threads);
	    //cast to pointer from integer of different size ，意思为指针和整型两种类型的大小不一致。
            
            if (res != 0){
                char * str;
                sprintf(str,"[%d] pthread_create failure",lots_of_threads);
                perror(str);
                exit(EXIT_FAILURE);
            }
//            sleep(1);

//	    printf("---[%d]---\n",lots_of_threads);
    }
 //   sleep(1);
    printf("Waiting for threads to finish...\n");
    pthread_mutex_destroy(&mutex);
    for(lots_of_threads =NUM_THREAD -1;lots_of_threads >=0;lots_of_threads--){
        res = pthread_join(a_thread[lots_of_threads],&thread_result);
        if (res != 0){
                char * str;
                sprintf(str,"[%d] pthread_create failure",lots_of_threads);
                perror(str);
                exit(EXIT_FAILURE);
        }
    }
    printf("All done\n");
    exit(EXIT_SUCCESS);
}

void * thread_function(void * arg)
{
    
	while(fakelock) {}
    pthread_mutex_lock(&mutex);
    fakelock = 1;
    pthread_mutex_unlock(&mutex);

   int my_number = *(int*)arg ;
   int rand_num;

   printf("thread[%d] is running\n",my_number);
   
  rand_num = 1 + (9*rand() / (RAND_MAX + 1.0)) ;

//  sleep(rand_num);
  printf("Bye Form %d\n",my_number);
  pthread_exit(NULL);
}

